#!/usr/bin/python
# -*- coding: utf-8 -*-

from flask_restful import Resource
from flask         import redirect,request,make_response,abort

from urllib.parse import parse_qs, urlparse

from e4ting       import log,util
from e4ting.api   import CasDoor
from config       import FlaskConf

class WebSite(Resource):
    ''' 静态页面鉴权 '''
    #----------------------------------------------------------------------
    def __init__(self):
        super(WebSite, self).__init__()

    def init(self):
        # log.info(request.headers)
        self.Method = request.headers.get("X-Original-Method", "") or ""
        self.API    = request.headers.get("X-Original-API", "") or ""

        self.Url    = request.headers.get("X-Original-Url", "") or ""
        self.Href   = request.headers.get("X-Original-Href", "") or ""

        self.Ip     = request.headers.get("X-Real-Ip", "") or ""
        self.Host   = request.headers.get("Host", "") or ""

        if "code=" in self.Url:
            self.code = parse_qs(urlparse(self.Url).query).get("code", [None])[0]
        elif "code=" in self.Href:
            self.code = parse_qs(urlparse(self.Href).query).get("code", [None])[0]
        else:
            self.code = request.cookies.get('token')

        log.info("Method={self.Method},API={self.API},href={self.Href},Url={self.Url},Ip={self.Ip},Host={self.Host},code={self.code}".format(self=self))

    def verify_code(self, cas):
        if not self.code:
            abort(401)
        if not cas.check_code(code=self.code, refer=self.Url, client_ip=self.Ip):
            # code 校验没通过，如果通过里面会交换token
            abort(401)
        self.token = cas.code_swap_token(self.code)
        if not cas.check_token(self.token):
            # token 校验不通过
            abort(401)

    def get(self, **kwargs):
        self.init()

        cas = CasDoor(casdoor_host=FlaskConf.CASDOOR_HOST, client_id=FlaskConf.CASDOOR_ID, client_secret=FlaskConf.CASDOOR_SECRET)
        self.verify_code(cas)
        resp = make_response(self.code)
        # 设置 Cookie
        resp.set_cookie('token', self.code, max_age=3600*24, path='/', domain=self.Host, httponly=False)

        # 返回响应对象
        return resp